// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;
using SnapObjects.Commons;

namespace SnapObjects.Data.Odbc
{
    public class OdbcAseTypeMapper : TypeMapper
    {
        //string
        private readonly OdbcCharTypeMapping _char = new OdbcCharTypeMapping("char", dbType: DbType.AnsiString);
        private readonly OdbcAseByteArrayTypeMapping _unboundedBinary = new OdbcAseByteArrayTypeMapping("varbinary(max)");
        private readonly OdbcAseStringTypeMapping _unboundedUnicodeString = new OdbcAseStringTypeMapping("nvarchar(max)", dbType: null, unicode: true);
        private readonly OdbcAseStringTypeMapping _keyUnicodeString = new OdbcAseStringTypeMapping("nvarchar(450)", dbType: null, unicode: true, size: 450);
        private readonly OdbcAseStringTypeMapping _unboundedAnsiString = new OdbcAseStringTypeMapping("varchar(max)", dbType: DbType.AnsiString);
        private readonly OdbcAseStringTypeMapping _keyAnsiString = new OdbcAseStringTypeMapping("varchar(900)", dbType: DbType.AnsiString, unicode: false, size: 900);
        private readonly OdbcAseStringTypeMapping _fixedLengthUnicodeString = new OdbcAseStringTypeMapping("nchar", dbType: DbType.String, unicode: true);
        private readonly OdbcAseStringTypeMapping _variableLengthUnicodeString = new OdbcAseStringTypeMapping("nvarchar", dbType: null, unicode: true);
        private readonly OdbcAseStringTypeMapping _fixedLengthAnsiString = new OdbcAseStringTypeMapping("char", dbType: DbType.AnsiString);
        private readonly OdbcAseStringTypeMapping _variableLengthAnsiString = new OdbcAseStringTypeMapping("varchar", dbType: DbType.AnsiString);
        private readonly OdbcAseStringTypeMapping _text = new OdbcAseStringTypeMapping("text", dbType: DbType.AnsiString, unicode: false);
        private readonly OdbcAseStringTypeMapping _ntext = new OdbcAseStringTypeMapping("ntext", dbType: DbType.String, unicode: true);

        //number
        private readonly IntTypeMapping _int = new IntTypeMapping("int", DbType.Int32);
        private readonly LongTypeMapping _long = new LongTypeMapping("unsigned int", DbType.Int64);
        private readonly ShortTypeMapping _short = new ShortTypeMapping("smallint", DbType.Int16);
        private readonly ByteTypeMapping _byte = new ByteTypeMapping("tinyint", DbType.Byte);
        private readonly OdbcFloatTypeMapping _float = new OdbcFloatTypeMapping("float", DbType.Single);
        private readonly OdbcDoubleTypeMapping _double = new OdbcDoubleTypeMapping("double precision", DbType.Double);
        private readonly DecimalTypeMapping _decimal = new DecimalTypeMapping("decimal", DbType.Double);

        private readonly UIntTypeMapping _uint = new UIntTypeMapping("uint", DbType.Int64);
        private readonly ULongTypeMapping _ulong = new ULongTypeMapping("ulong", DbType.Int64);
        private readonly UShortTypeMapping _ushort = new UShortTypeMapping("ushort", DbType.Int32);

        //binary
        private readonly OdbcAseByteArrayTypeMapping _image = new OdbcAseByteArrayTypeMapping("Image");
        private readonly OdbcAseByteArrayTypeMapping _fixedLengthBinary = new OdbcAseByteArrayTypeMapping("binary");
        private readonly OdbcAseByteArrayTypeMapping _variableLengthBinary = new OdbcAseByteArrayTypeMapping("varbinary");
        private readonly OdbcAseByteArrayTypeMapping _keyBinary = new OdbcAseByteArrayTypeMapping("varbinary(900)", dbType: DbType.Binary, size: 900);

        //date
        private readonly OdbcAseDateTimeTypeMapping _date = new OdbcAseDateTimeTypeMapping("date", dbType: DbType.Date);
        private readonly OdbcAseDateTimeTypeMapping _datetime = new OdbcAseDateTimeTypeMapping("datetime", dbType: DbType.DateTime);
        private readonly OdbcDateTimeOffsetTypeMapping _datetimeoffset = new OdbcDateTimeOffsetTypeMapping("datetimeoffset");
        private readonly OdbcAseTimeTypeMapping _time = new OdbcAseTimeTypeMapping("time", DbType.Time);

        //other
        private readonly BoolTypeMapping _bool = new BoolTypeMapping("bit", DbType.Boolean);
        private readonly GuidTypeMapping _uniqueidentifier = new GuidTypeMapping("uniqueidentifier", DbType.Guid);

        protected HashSet<string> _disallowedMappings;
        protected Dictionary<string, TypeMapping> _dbTypeMappings;
        protected Dictionary<Type, TypeMapping> _clrTypeMappings;

        public OdbcAseTypeMapper(IDataContextOptions options) : base(options)
        {
            _dbTypeMappings = new Dictionary<string, TypeMapping>(StringComparer.OrdinalIgnoreCase)
            {
                { "bigdatetime", _datetime},
                { "bigint", _long },
                { "bigtime", _time},
                { "binary", _fixedLengthBinary },
                { "bit", _bool },
                { "char", _fixedLengthAnsiString },
                { "date", _date },
                { "datetime", _datetime },
                { "decimal", _decimal },
                { "double precision", _double },
                { "float", _double },
                { "image", _image },
                { "int", _int },
                { "longsysname", _fixedLengthUnicodeString},
                { "money", _decimal },
                { "nchar", _fixedLengthUnicodeString },
                { "ntext", _ntext },
                { "numeric", _decimal },
                { "nvarchar", _variableLengthUnicodeString },
                { "real", _float },
                { "smalldatetime", _datetime },
                { "smallint", _short },
                { "smallmoney", _decimal },
                { "text", _text },
                { "time", _time },
                { "timestamp", _fixedLengthBinary },
                { "tinyint", _byte },
                { "unichar", _fixedLengthUnicodeString},
                { "univarchar", _variableLengthUnicodeString},
                { "unitext", _ntext},
                { "ubigint", _ulong },
                { "uint", _uint},
                { "usmallint", _ushort},
                { "unsigned bigint", _decimal },
                { "unsigned int", _long },
                { "unsigned smallint", _int },
                { "varbinary", _variableLengthBinary },
                { "varchar", _variableLengthAnsiString },
            };

            // Note: sbyte, ushort, uint, char and ulong type mappings are not supported by SQL Server.
            // We would need the type conversions feature to allow this to work - see https://github.com/aspnet/EntityFramework/issues/242.
            _clrTypeMappings = new Dictionary<Type, TypeMapping>
            {
                { typeof(int), _int },
                { typeof(long), _long },
                { typeof(DateTime), _datetime },
                { typeof(Guid), _uniqueidentifier },
                { typeof(bool), _bool },
                { typeof(byte), _byte },
                { typeof(double), _double },
                { typeof(float), _float },
                { typeof(DateTimeOffset), _datetimeoffset },
                { typeof(short), _short },
                { typeof(decimal), _decimal },
                { typeof(TimeSpan), _time },
                { typeof(char), _char },
                { typeof(ulong), _ulong},
                { typeof(uint), _uint},
                { typeof(ushort), _ushort}
            };

            // These are disallowed only if specified without any kind of length specified in parenthesis.
            // This is because we don't try to make a new type from this string and any max length value
            // specified in the model, which means use of these strings is almost certainly an error, and
            // if it is not an error, then using, for example, varbinary(1) will work instead.
            _disallowedMappings = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
            {
                "binary varying",
                "binary",
                "char varying",
                "char",
                "character varying",
                "character",
                "national char varying",
                "national character varying",
                "national character",
                "nchar",
                "nvarchar",
                "varbinary",
                "varchar"
            };

            this.ByteArrayMapper = new ByteArrayTypeMapper(
               maxBoundedLength: 8000,
               defaultMapping: _unboundedBinary,
               unboundedMapping: _unboundedBinary,
               keyMapping: _keyBinary,
               createBoundedMapping: size => new OdbcAseByteArrayTypeMapping(
                   "varbinary(" + size + ")",
                   DbType.Binary,
                   size));

            this.StringMapper = new StringTypeMapper(
                maxBoundedAnsiLength: 8000,
                defaultAnsiMapping: _unboundedAnsiString,
                unboundedAnsiMapping: _unboundedAnsiString,
                keyAnsiMapping: _keyAnsiString,
                createBoundedAnsiMapping: size => new OdbcAseStringTypeMapping(
                    "varchar(" + size + ")",
                    DbType.AnsiString,
                    unicode: false,
                    size: size),
                maxBoundedUnicodeLength: 4000,
                defaultUnicodeMapping: _unboundedUnicodeString,
                unboundedUnicodeMapping: _unboundedUnicodeString,
                keyUnicodeMapping: _keyUnicodeString,
                createBoundedUnicodeMapping: size => new OdbcAseStringTypeMapping(
                    "nvarchar(" + size + ")",
                    dbType: null,
                    unicode: true,
                    size: size));
        }

        public override IByteArrayTypeMapper ByteArrayMapper { get; }

        public override IStringTypeMapper StringMapper { get; }

        public override void ValidateTypeName(string dbTypeName)
        {
            if (_disallowedMappings.Contains(dbTypeName))
            {
                throw new ArgumentException(OdbcStrings.UnqualifiedDataType(dbTypeName));
            }
        }

        public override TypeMapping FindMapping(Type clrType)
        {
            Check.NotNull(clrType, nameof(clrType));

            clrType = TypeHelper.UnwrapEnumType(TypeHelper.UnwrapNullableType(clrType));

            return clrType == typeof(string)
                ? _unboundedUnicodeString
                : (clrType == typeof(byte[]) ? _unboundedBinary : base.FindMapping(clrType));
        }

        protected override IReadOnlyDictionary<Type, TypeMapping> GetClrTypeMappings()
        {
            return _clrTypeMappings;
        }

        protected override IReadOnlyDictionary<string, TypeMapping> GetDbTypeMappings()
        {
            return _dbTypeMappings;
        }
    }
}
